//@flow

/**
 * 验证码按钮
 * 1，发送验证码
 * 2，发送成功，倒计时
 * 3，回归“发送验证码”
 */

import React, { Component } from 'react';
import { 
    View,
    Text,
    TouchableOpacity,
    StyleSheet,
 } from 'react-native';

/**验证码发送结果回调 */
type CodeSendRes = (res:boolean)=>{}
/**发送验证码间隔时间 */
const TIME_LONG_SEND_AGAIN : number = 3

type State = {
    canSendCode :boolean,//如果已经发送过验证码，则阻断1分钟发送
    label       :string,//按钮文字的显示
    remind      :number,//再次发送剩余时间
}

export class AuthCodeBtn extends Component<{},State> {
    
    /**初始化state */
    state : State = {
        canSendCode	:true,
        label:'发送验证码',
        remind:0,
    }
    /**发送验证码事件触发 
     * 1,开始倒计时
     * 2，修改状态
    */
    onClickSendCode(){
        this.sendCode().then(res=>{
            if(res){
                this.setState({
                    canSendCode:false,
                    remind:TIME_LONG_SEND_AGAIN,
                    label:'再次发送'
                },()=>{
                    this.countDownTimer = setInterval(()=>{
                        if(this.state.remind-1>0){
                            this.setState({remind:this.state.remind-1,label:`再次发送${this.state.remind-1}`})
                        }else{
                            this.resetCodeStatus()
                        }
                    },1000)
                })
            }else{

            }
        })
    }
    /**重置验证码发送状态 
     * 同时清除定时器
    */
    resetCodeStatus(){
        //清楚定时器
        clearInterval(this.countDownTimer)
        this.setState({
            canSendCode:true,
            label:'发送验证码',
            remind:TIME_LONG_SEND_AGAIN,
        })
        
    }
    /**发送验证码请求 */
    sendCode():Promise<CodeSendRes>{
        return new Promise((resolve,reject)=>{
            resolve(true)
        })
    }
    render(){
        const {
            canSendCode,
        } = this.state;
        return (
            <TouchableOpacity
                style={{paddingHorizontal:6,borderLeftWidth:1,borderColor:'white'}}
                disabled={!canSendCode}
                onPress={()=>{
                        this.onClickSendCode()
                }}>
                <Text style={{color:canSendCode?'rgb(0,153,255)':'gray'}}>{this.state.label}</Text>
            </TouchableOpacity>
        )
    }
}

